<template>
  <div class="container">

  </div>
</template>

<script>
  import * as d3 from 'd3'

  export default {
    name: 'HelloWorld',
    data() {
      return {
        //设置宽高
        width:800,
        height:500,
        //在画布上显示的节点和关系
        links:[{"source": " ", "target": " ", "value": 1}],
        nodes:[],
        //节点名称
        nodeName:"",
        simulation:null,
        //颜色列表
        colorList:['red','yellow','#123501','#223344','yellow','black','#002266',
          '#ffee11','#aebc23','red','blue','#123501','#223344',
          'yellow','black','#002266','#ffee11','#aebc23'],
        //节点和关系的数据
        testGraph: {
          "links":[],
          "nodes":[],
        }
      }
    },
    created() {
      const _this=this;
      //向后端发送请求
      // this.axios.get("http://localhost:8329/api/person/Tom Cruise")
      this.axios.get("http://localhost:8329/api/person/all")
        .then(function (response) {
          _this.testGraph["nodes"]=response.data
          //异步的 不然还是空数据
          //初始化节点和关系
          _this.init(_this.testGraph)
        })
        .catch(function (response) {
          console.log(response)
        })

    },
    methods: {
      init(data) {
        const _this=this;
        //去掉无影响
        // const links = data.links.map(d => Object.create(d));
        // const nodes = data.nodes.map(d => Object.create(d));
        const links = data.links;
        const nodes = data.nodes;
        //设置力的导向等...
        _this.simulation = d3.forceSimulation(nodes)
          //结点碰撞
          // .force("collide",d3.forceCollide().radius(()=>30))
          .force("link", d3.forceLink(links).id(d => d.id).distance(100))
          .force("charge", d3.forceManyBody().strength(-30))
          .force("center", d3.forceCenter(_this.width / 2, _this.height / 2));

        //用来放node和link的容器
        //选中container类 SVG 意为可缩放矢量图形。
        const svg=d3.select(".container")
          //添加一个svg元素
          .append("svg")
          //添加一个视图盒子  设置宽高
          .attr("viewBox", [0, 0, _this.width, _this.height])
          //设置滚轮缩小放大
          .call(d3.zoom().on("zoom",function () {
            g.attr("transform",d3.event.transform)
          }))
        //svg中添加一个g元素 并设置类名
        const g = svg.append("g")
          .attr("class","content")

        //设置关系
        _this.links = g.append("g")
          //元素轮廓颜色
          .attr("stroke", "#999")
          //边框颜色的透明度
          .attr("stroke-opacity", 0.6)
          //'join'  data中的每个数据到selection中的每个元素上
          .selectAll("line")
          .data(links)
          .join("line")
          //边框宽度
          .attr("stroke-width", d => Math.sqrt(d.value))
          //添加类属性
          .attr("class","link");

        _this.nodes = g.append("g")
          //'join'  data中的每个数据到selection中的每个元素上
          .selectAll("circle")
          .data(nodes,d=>d.id)
          .join("circle")
          //设置半径
          .attr("r", 30)
          //给圆填充颜色
          .attr("fill", this.color)
          //添加拖动事件
          .call(this.drag(_this.simulation))
          //添加类名
          .classed("node",true)
          //添加点击事件 好像没用
          .on("click",this.nodeClick)

        //给node加一个名字 鼠标放上去显示
        _this.nodes.append("title")
          .text(d => d.id);
        //把名字加到圆的下面
        _this.nodeName=g.append("g")
          //'join'  data中的每个数据到selection中的每个元素上
          .selectAll("text")
          .data(nodes)
          .join("text")
          //类名
          .attr("class","nodeName")
          //设置文本内容
          .text(d => d.id)
          //文字填充白色
          .attr("fill","white")
          //x y 相对于圆心的偏移量
          .attr("dy",50)
          .attr("dx",function () {
            return this.getBoundingClientRect().width/2*(-1)
          })

        _this.simulation.on("tick", () => {
          _this.links
            .attr("x1", d => d.source.x)
            .attr("y1", d => d.source.y)
            .attr("x2", d => d.target.x)
            .attr("y2", d => d.target.y);

          _this.nodes
            .attr("cx", d => d.x)
            .attr("cy", d => d.y);

          _this.nodeName
            .attr("x",d=>d.x)
            .attr("y",d=>d.y)
        });

      },
      color(d){
        //自己写个颜色数组测试
        return this.colorList[d.group]
        // const scale = d3.scaleOrdinal(d3.schemeCategory10);
        // return d => scale(d.group);
      },
      drag(simulation) {
        function dragstarted(d) {
          if (!d3.event.active) simulation.alphaTarget(0.3).restart();
          d.fx = d.x;
          d.fy = d.y;
        }

        function dragged(d) {
          d.fx = d3.event.x;
          d.fy = d3.event.y;
        }

        function dragended(d) {
          if (!d3.event.active) simulation.alphaTarget(0.5);
          d.fx = null
          d.fy = null
        }

        return d3.drag()
          .on("start", dragstarted)
          .on("drag", dragged)
          .on("end", dragended);
      },
      nodeClick(d) {
        const _this=this;
        //向后端发送请求 获取和人有关的电影信息
        this.axios.get("http://localhost:8329/api/person/actedby/"+d.id)
          .then(function (response) {
            //防止重复点击
            for(var i=0;i<response.data.length;i++){
              let flag=true;
              for(var j=0;j<_this.testGraph.nodes.length;j++){
                if(_this.testGraph.nodes[j].id===response.data[i].id){
                  flag=false;
                  break;
                }
              }
              if(flag){
                _this.testGraph.nodes.push(response.data[i])
                //把查询到的电影加进links中
                _this.testGraph.links.push({
                  "source": d.id,
                  "target": response.data[i].id,
                  "value": 5
                })
                console.log(_this.testGraph)
              }
            }
            //更新点击节点之后的信息
            _this.updateGraph(_this.testGraph)
          })
          .catch(function (response) {
            console.log(response)
          })
      },
      updateGraph(data){
        const _this=this;
        const links = data.links;
        const nodes = data.nodes;

        _this.links=_this.links
          .data(links,(d)=>{return d.source.id+"-"+d.target.id;})
          .enter()
          .append("line")
          .attr("stroke", "#999")
          .attr("stroke-opacity", 0.6)
          .attr("stroke-width", d => Math.sqrt(d.value))
          .merge(_this.links)
          .attr("class","link")

        _this.nodes = _this.nodes
          .data(nodes)
          .enter()
          .append("circle")
          .attr("r", 30)
          .attr("class","node")
          .attr("fill", this.color)
          .merge(_this.nodes)
          .on("click",this.nodeClick)
          .call(_this.drag(_this.simulation))


        _this.nodes.append("title")
          .text(d => d.id);
        _this.nodeName=_this.nodeName
          .data(nodes)
          .join("text")
          .attr("class","nodeName")
          .text(d => d.id)
          .attr("fill","white")
          .attr("dy",50)
          .attr("dx",function () {
            return this.getBoundingClientRect().width/2*(-1)
          })
        _this.simulation.nodes(nodes)
        _this.simulation.force("link").links(links)
        _this.simulation.alpha(0.2).restart()
      }
    }
  }
</script>


<style >
  body{
    margin: 0px;
  }
  .container{
    width: 800px;
    height: 500px;
    border: 1px solid #2c3e50;
    border-radius:8px;
    margin-top: 40px;
    margin-left: auto;
    margin-right: auto;
    background: #154360 repeating-linear-gradient(30deg,
    hsla(0, 0%, 100%, .1), hsla(0, 0%, 100%, .1) 15px,
    transparent 0, transparent 30px);
  }
  .node{
    stroke:#fff;
    stroke-width:1;
    cursor: pointer;
  }
  .node:hover{
    stroke-width:5;
  }
  .nodeName{
    fill:white;
  }
</style>
